<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="6" v-for="(item, index) in statCards" :key="index">
        <div class="stat-card">
          <div class="stat-icon" :style="{ backgroundColor: item.color }">
            <span class="icon-emoji">{{ item.icon }}</span>
          </div>
          <div class="stat-info">
            <div class="stat-title">{{ item.title }}</div>
            <div class="stat-value">{{ item.value }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <!-- 同步任务状态 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>同步任务状态</span>
              <el-button type="primary" link>查看全部</el-button>
            </div>
          </template>
          <div class="chart-container">
            <div ref="taskStatusChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 同步数据量趋势 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>同步数据量趋势</span>
              <el-button type="primary" link>查看详情</el-button>
            </div>
          </template>
          <div class="chart-container">
            <div ref="dataVolumeChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <!-- 最近同步任务 -->
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近同步任务</span>
              <el-button type="primary" link @click="$router.push('/task')">查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentTasks" style="width: 100%" v-loading="loading">
            <el-table-column prop="name" label="任务名称" min-width="180" />
            <el-table-column prop="source_name" label="源数据源" min-width="120" />
            <el-table-column prop="target_name" label="目标数据源" min-width="120" />
            <el-table-column prop="sync_type" label="同步类型" min-width="100">
              <template #default="{ row }">
                <el-tag :type="row.sync_type === 'full' ? 'primary' : 'success'">
                  {{ row.sync_type === 'full' ? '全量同步' : '增量同步' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="last_sync_time" label="最近同步时间" min-width="180" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="$router.push(`/task/edit/${row.id}`)">编辑</el-button>
                <el-button type="primary" link @click="$router.push(`/task/log/${row.id}`)">日志</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
// 暂时移除图标导入，使用文字图标
// import { getTaskList } from '@/api/task'
// import { getSyncCountStats, getSyncSuccessRateStats } from '@/api/stats'
// import { getRealTimeSyncStatus } from '@/api/monitor'

const router = useRouter()
const loading = ref(false)
const recentTasks = ref([])
const taskStatusChart = ref(null)
const dataVolumeChart = ref(null)
let taskStatusChartInstance = null
let dataVolumeChartInstance = null

// 统计卡片数据
const statCards = ref([
  { title: '数据源总数', value: 0, icon: '📊', color: '#1890ff' },
  { title: '同步任务总数', value: 0, icon: '🔗', color: '#52c41a' },
  { title: '今日同步数据量', value: 0, icon: '📈', color: '#faad14' },
  { title: '同步成功率', value: '0%', icon: '✅', color: '#ff4d4f' }
])

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'running': 'primary',
    'success': 'success',
    'failed': 'danger',
    'stopped': 'info',
    'waiting': 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'running': '运行中',
    'success': '成功',
    'failed': '失败',
    'stopped': '已停止',
    'waiting': '等待中'
  }
  return statusMap[status] || '未知'
}

// 初始化任务状态图表
const initTaskStatusChart = () => {
  if (taskStatusChartInstance) {
    taskStatusChartInstance.dispose()
  }
  
  taskStatusChartInstance = echarts.init(taskStatusChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '任务状态',
        type: 'pie',
        radius: '70%',
        data: [
          { value: 10, name: '运行中', itemStyle: { color: '#409EFF' } },
          { value: 40, name: '成功', itemStyle: { color: '#67C23A' } },
          { value: 5, name: '失败', itemStyle: { color: '#F56C6C' } },
          { value: 15, name: '已停止', itemStyle: { color: '#909399' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  taskStatusChartInstance.setOption(option)
}

// 初始化数据量趋势图表
const initDataVolumeChart = () => {
  if (dataVolumeChartInstance) {
    dataVolumeChartInstance.dispose()
  }
  
  dataVolumeChartInstance = echarts.init(dataVolumeChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['同步数据量', '成功数量', '失败数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '同步数据量',
        type: 'line',
        stack: 'Total',
        data: [120, 132, 101, 134, 90, 230, 210],
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '成功数量',
        type: 'line',
        stack: 'Total',
        data: [110, 122, 91, 124, 80, 220, 200],
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '失败数量',
        type: 'line',
        stack: 'Total',
        data: [10, 10, 10, 10, 10, 10, 10],
        itemStyle: { color: '#F56C6C' }
      }
    ]
  }
  
  dataVolumeChartInstance.setOption(option)
}

// 获取最近同步任务
const fetchRecentTasks = async () => {
  loading.value = true
  try {
    // 模拟数据
    recentTasks.value = [
      {
        id: 1,
        name: '用户数据同步',
        source_name: 'MySQL-主库',
        target_name: 'MongoDB-备份',
        sync_type: 'full',
        status: 'success',
        last_sync_time: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        name: '订单数据同步',
        source_name: 'MySQL-订单库',
        target_name: 'MySQL-数仓',
        sync_type: 'incremental',
        status: 'running',
        last_sync_time: '2024-01-15 11:00:00'
      }
    ]
  } catch (error) {
    console.error('获取最近同步任务失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    // 这里应该调用实际的API获取统计数据
    // 暂时使用模拟数据
    statCards.value[0].value = 8
    statCards.value[1].value = 15
    statCards.value[2].value = 12580
    statCards.value[3].value = '98.5%'
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  taskStatusChartInstance && taskStatusChartInstance.resize()
  dataVolumeChartInstance && dataVolumeChartInstance.resize()
}

onMounted(() => {
  fetchRecentTasks()
  fetchStats()
  
  // 等待DOM渲染完成后初始化图表
  setTimeout(() => {
    initTaskStatusChart()
    initDataVolumeChart()
  }, 100)
  
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  taskStatusChartInstance && taskStatusChartInstance.dispose()
  dataVolumeChartInstance && dataVolumeChartInstance.dispose()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 0;
  background: transparent;
}

.mt-20 {
  margin-top: 24px;
}

:deep(.el-card) {
  border: 1px solid var(--border-light);
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-light);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: var(--shadow-medium);
    transform: translateY(-2px);
  }
  
  .el-card__header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-light);
    background: linear-gradient(135deg, #fafbfc 0%, #f8fafc 100%);
  }
  
  .el-card__body {
    padding: 24px;
  }
}

.stat-card {
  height: 120px;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border: 1px solid var(--border-light);
  border-radius: var(--radius-medium);
  padding: 24px;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--primary-color) 0%, var(--primary-light) 100%);
  }
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  }
  
  .stat-icon {
    width: 64px;
    height: 64px;
    border-radius: var(--radius-medium);
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 20px;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      inset: 0;
      border-radius: var(--radius-medium);
      background: inherit;
      opacity: 0.1;
    }
    
    .el-icon {
      font-size: 28px;
      color: #fff;
      position: relative;
      z-index: 1;
    }
    
    .icon-emoji {
      font-size: 28px;
      position: relative;
      z-index: 1;
    }
  }
  
  .stat-info {
    flex: 1;
    
    .stat-title {
      font-size: 14px;
      color: var(--text-secondary);
      margin-bottom: 8px;
      font-weight: 500;
    }
    
    .stat-value {
      font-size: 32px;
      font-weight: 700;
      color: var(--text-primary);
      line-height: 1;
      background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  span {
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
  }
  
  .el-button {
    font-weight: 500;
  }
}

.chart-container {
  height: 320px;
  padding: 16px 0;
  
  .chart {
    width: 100%;
    height: 100%;
    border-radius: var(--radius-small);
  }
}

:deep(.el-table) {
  border-radius: var(--radius-medium);
  overflow: hidden;
  
  .el-table__header {
    background: var(--bg-tertiary);
    
    th {
      background: transparent;
      color: var(--text-primary);
      font-weight: 600;
      border-bottom: 1px solid var(--border-light);
    }
  }
  
  .el-table__body {
    tr {
      transition: background-color 0.2s ease;
      
      &:hover {
        background: var(--bg-tertiary);
      }
    }
    
    td {
      border-bottom: 1px solid var(--border-light);
      padding: 16px 12px;
    }
  }
}

:deep(.el-tag) {
  border-radius: var(--radius-small);
  font-weight: 500;
  padding: 4px 12px;
  
  &.el-tag--primary {
    background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
    border-color: var(--primary-light);
    color: var(--primary-dark);
  }
  
  &.el-tag--success {
    background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
    border-color: #95de64;
    color: #389e0d;
  }
  
  &.el-tag--danger {
    background: linear-gradient(135deg, #fff2f0 0%, #ffccc7 100%);
    border-color: #ff7875;
    color: #cf1322;
  }
  
  &.el-tag--info {
    background: linear-gradient(135deg, #f0f5ff 0%, #d6e4ff 100%);
    border-color: #91d5ff;
    color: #0958d9;
  }
  
  &.el-tag--warning {
    background: linear-gradient(135deg, #fffbe6 0%, #fff1b8 100%);
    border-color: #ffd666;
    color: #d48806;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .stat-card {
    .stat-value {
      font-size: 28px;
    }
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }
  
  .stat-card {
    padding: 16px;
    
    .stat-icon {
      width: 48px;
      height: 48px;
      margin-right: 16px;
      
      .el-icon {
        font-size: 20px;
      }
    }
    
    .stat-info {
      .stat-value {
        font-size: 24px;
      }
    }
  }
  
  .chart-container {
    height: 250px;
  }
}
</style>